package cash.cmp.personal_financial_system.service.impl;

import cash.cmp.personal_financial_system.mapper.AccountMapper;
import cash.cmp.personal_financial_system.mapper.UserMapper;
import cash.cmp.personal_financial_system.model.account.Account;
import cash.cmp.personal_financial_system.model.Role;
import cash.cmp.personal_financial_system.model.User;
import cash.cmp.personal_financial_system.model.ro.WxUserInfoRO;
import cash.cmp.personal_financial_system.service.AccountService;
import cash.cmp.personal_financial_system.utils.login_else.AlipayLoginUtil;
import cash.cmp.personal_financial_system.utils.Result;
import cash.cmp.personal_financial_system.utils.login_else.WxLoginUtil;
import com.alipay.api.AlipayApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
//配置事务回滚
@Transactional(rollbackFor = Exception.class)
public class AccountServiceImpl implements AccountService {


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AccountMapper accountMapper;

    @Override
    //注册直接调用AccountService的register方法
    public Result register(String tel, String password, String username) {

        if (password == null) {
            return Result.fail("密码不能为空");
        }

        tel = tel.trim();
        if (tel.length() == 0) {
            return Result.fail("电话不能为空");
        }


        if (password.length() == 0) {
            return Result.fail("密码不能为空");
        }

        if (password.length() > 20) {
            return Result.fail("密码长度不能大于20");
        }

        //两次密码输入是否一致验证不要放在后端，这里我给你删了
        // 插入数据库接口，account、user
        //记住顺序，一定是先插入account，再插入user，因为user的id字段外键是account的id
        //首先在数据库里查找是否存在该手机号，不存在则可以注册
        Account accountF = accountMapper.getAccount(tel);
        if(accountF == null){
            // 密码hash , 存对用的密码hash至数据库
            Account account = new Account();
            account.setTel(tel);
            account.setPassword(password);
            //这个地方自动注入自增的id，会注入到你传入的Account中，所以只要给Account设置密码，然后使用register方法
            //你传入的Account会自动注入新增的id，再在之后放入User中
            accountMapper.register(account);
            //给予权限
            accountMapper.giveAccountRolesById(account.getId(),"normal");
            User user = new User();
            user.setId(account.getId());
            //一定要放注册时间
            user.setRegister(new Date());
            user.setTel(tel);
            user.setName(username);
            user.setHeadImage("image_default");
            userMapper.insertUser(user);

            return Result.succ(200,"success",null);
        }
        return Result.fail("该用户已存在");
    }

    @Override
    public Account accountLogin(String tel, String password){
        return accountMapper.accountLogin(tel,password);
    }

    @Override
    public Account getAccount(String tel) {
        return accountMapper.getAccount(tel);
    }

    @Override
    public List<Role> getAccountRolesById(Integer id) {
        return accountMapper.getAccountRolesById(id);
    }

    @Override
    public Boolean giveAccountRolesById(Integer id, String name) {
        return accountMapper.giveAccountRolesById(id,name);
    }

    @Override
    public Boolean updateAccount(Account account) {
        return accountMapper.updateAccount(account);
    }

    @Override
    public Boolean updateObjectID(Integer id, Integer objectId){
        return accountMapper.updateObjectID(id,objectId);
    }
    @Override
    public Boolean deleteAccount(Integer id) {
        return accountMapper.deleteAccount(id);
    }

    @Override
    public Boolean saveList(List<Account> list) {
        return accountMapper.saveList(list);
    }

    @Override
    public Account loginByWx(String code){
        //1.通过code 获取到用户的微信信息
        WxUserInfoRO wxUserInfoRO = WxLoginUtil.toWxLogin(code);
        System.out.println(wxUserInfoRO);
        //2.数据库对比 unionid 是否已有信息 如果没有无法登录
        User user = userMapper.findUserByWechat(wxUserInfoRO.getUnionid());
//        System.out.println(wxUserInfoRO.getUnionid());
        //通过查询pk_id 索引优化查询 无需回表查询用户信息 索引 unionid
        if(user == null ) {
            return null;
        }
        Account account = accountMapper.getAccount(user.getTel());
        return account;
    }

    @Override
    public Account loginByApiPay(String code) throws AlipayApiException, IOException {
        //1.通过code 获取到用户的token
        String Token = AlipayLoginUtil.getToken(code);
        //2.通过Token 获取到用户的信息
        Map<String, String> userInfo = AlipayLoginUtil.getUserInfo(Token);
        System.out.println(userInfo);
        // System.out.println(userInfo.get("userId"));
        User user = userMapper.findUserByAlipay(userInfo.get("userId"));
        //通过查询pk_id 索引优化查询 无需回表查询用户信息 索引 unionid
        if(user == null ) {
            return null;
        }
        Account account = accountMapper.getAccount(user.getTel());
        return account;
    }
}
